<template>
	<view>
		<z-nav-bar backState="1000">{{title}}</z-nav-bar>
		
		<view class="u-p-30">
			<u-form labelPosition="left" :model="model" :rules="rules" ref="uForm" :errorType="errorType">
				<u-form-item label="收货人：" label-width="80" prop="contacts" >
					<u-input placeholder="请输入名字" border="none" v-model="model.contacts" type="text" ></u-input>
				</u-form-item>
				
				<u-form-item label="手机号：" label-width="80" label-position="left" prop="contactNumber" >
					<u-input placeholder="请输入手机号" border="none" v-model="model.contactNumber" type="number" ></u-input>
				</u-form-item>
				
				<u-form-item label="所在地区：" label-width="80" label-position="left" prop="province" >
					<view class="u-flex u-flex-end" @click="handleArea">
						<text>{{userArea ? userArea : '请选择'}}</text>
						<u-icon name="arrow-right"></u-icon>
					</view>	
				</u-form-item>
				
				<u-form-item label="详细地址：" label-width="80" label-position="left" prop="address" >
					<u-input border="none" placeholder="请输入小区楼栋/乡村名称" v-model="model.address" type="textarea" ></u-input>
				</u-form-item>
				
				<u-form-item label="设为默认收货地址" label-width="180" label-position="left" prop="isDefault" >
					<view style="position: absolute;right: 30rpx;">
						<u-switch v-model="model.isDefault" activeValue="1" inactiveValue="0" activeColor="#FFB143" inactiveColor="#AAAAAA"></u-switch>
					</view>
				</u-form-item>
			</u-form>
			
			<view class="u-flex u-m-t-30">
				<view class="tag u-m-r-30" v-for="(item, index) in addressLabelList" @click="handleAddressLabel(item)"
							:class="{'tag-seleced': model.addressLabel === item}">
					{{item}}
				</view>
			</view>
			
			<!-- 地区 -->
			<u-picker keyName="name" :show="addressShow" ref="uPicker" @cancel="pickerCancel" :columns="columns"
								@confirm="confirm" @change="changeHandler">
			</u-picker>
			
			<view class="u-m-t-30 u-p-30">
				<u-button @click="handleSubmit"
						  shape="circle" 
						  :ripple="true" 
							:customStyle="{'color':'#FFFFFF', 'backgroundColor':'#FFB143'}"
						  type="error" >保存</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import areaList from '@/common/address-data'
	import {addAddress, updateAddress, addressInfo} from '@/api/address.js'
	
	export default{
		data(){
			return{
				areaList: areaList.list,
				title:'',
				model:{
					id:'',
					contacts:'',
					contactNumber:'',
					address:'',
					province:'',
					city:'',
					area:'',
					isDefault:'1',
					addressLabel:'家'
				},
				rules:{
					contacts:[
						{
							required: true,
							message: '请输入收货人',
							trigger: 'change'
						},
					],
					contactNumber: [
						{
							required: true,
							message: '请输入收货人电话',
							trigger: 'blur' ,
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: '手机号码格式不正确',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						}
					],
					province: [
						{
							required: true,
							message: '请选择所在地区',
							trigger: 'blur' ,
						},
					],
					address:[
						{
							required: true,
							message: '请输入收货地址',
							trigger: 'change'
						},
					]
				},
				errorType: 'toast',
				
				//三级联动组件展示框
				addressShow:false,
				//省市区数据
				columns: [
					[],
					[],
					[]
				],
				
				addressLabelList:['家', '公司', '学校']
				
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.uForm.setRules(this.rules)
		},
		computed:{
			userArea(){
				//let area = `${this.userInfo.province} ${this.userInfo.city}`
				let area = `${this.model.province} ${this.model.city} ${this.model.area}`
				return area.trim()
			}
		},
		onLoad(e) {
			this.columns[0] = this.areaList;
			this.columns[1] = this.areaList[0].cities;
			this.columns[2] = this.areaList[0].cities[0].districts;
			this.init(e)
		},
		methods:{
			init(e){
				if(e.id){
					// 编辑的场合
					this.title = "编辑地址"
					addressInfo({
						id:e.id
					}).then(res=>{
						this.model = res.data
					})
				} else {
					// 新增的场合
					this.title = "新增地址"
				}
			},
			
			
			/**
			 * 登录
			 */
			handleSubmit(){
				let that = this
				this.$refs.uForm.validate().then(res => {
					let data = JSON.parse(JSON.stringify(this.model))
					if(data.id){
						// 更新
						updateAddress(data).then(result=>{
							uni.showModal({
								title: '提示',
								content: '操作成功',
								showCancel:false,
								success: function (res) {
									that.navBack()
								}
							});
						})
					} else {
						// 添加
						addAddress(data).then(result=>{
							uni.showModal({
								title: '提示',
								content: '操作成功',
								showCancel:false,
								success: function (res) {
									that.navBack()
								}
							});
						})
					}
				}).catch(errors => {
					//uni.$u.toast('校验失败')
				})
			},
			
			/**
			 * 回退并刷新
			 */
			navBack(){
				var pages = getCurrentPages();
				var currPage = pages[pages.length - 1] //当前页面
				var prePage = pages[pages.length - 2] //上一个页面
				
				//调用上一页拉取数据的方法
				// if (prePage.route == "pages_one/address/index") {
				// 	// 上个界面刷新
				// 	prePage.$vm.reload()
				// }
				uni.$emit("reloadShopUserAddress")
				uni.navigateBack({})
			},
			
			handleArea(){
				this.addressShow = true
			},
			
			pickerCancel() {
				//隐藏联动展示框
				this.addressShow = false;
				//重置联动数据为初始状态
				this.$refs.uPicker.setIndexs([0, 0, 0], true);
				this.$refs.uPicker.setColumnValues(0, this.areaList);
				this.$refs.uPicker.setColumnValues(1, this.areaList[0].cities);
				this.$refs.uPicker.setColumnValues(2, this.areaList[0].cities[0].districts);
			},
			
			/**
			 * 点击确定事件,回调参数为包含columnIndex、value、values
			 */
			confirm(e) {
				//省
				this.model.province = e.value[0].name;
				//市
				this.model.city = e.value[1].name;
				//区
				this.model.area = e.value[2].name;
				//区域代码
				//this.userAddress.regionId = e.value[2].id;
				this.pickerCancel()
			},
			
			/**
			 * 三级联动框滑动选择后触发的事件
			 */
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					indexs,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.areaList[index].cities)
					picker.setColumnValues(2, this.areaList[indexs[0]].cities[0].districts)
				} else if (columnIndex === 1) {
					// picker为选择器this实例，变化第三列对应的选项
					picker.setColumnValues(2, this.areaList[indexs[0]].cities[indexs[1]].districts)
				}
			},
			
			/**
			 * 选择地址标签
			 */
			handleAddressLabel(item){
				this.model.addressLabel = item
			}
			
		}
	}
</script>

<style>
	page{
		background-color: #FFFFFF;
	}
</style>

<style scoped>
	.tag{
		padding: 5rpx 30rpx;
		background-color: #AAAAAA;
		border-radius: 12rpx;
		color: #FFFFFF;
	}
	
	.tag-seleced{
		padding: 5rpx 30rpx;
		background-color: #FFB143;
		border-radius: 12rpx;
	}
</style>